package com.xl.rentkeeper.business;

/**
 * Created by zhangjimin on 15/5/1.
 */

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

public class SingletonRegistry {
    public static SingletonRegistry sFactory = new SingletonRegistry();
    private static Map<Class,Object> map = new HashMap<>();
    protected SingletonRegistry() {
    }
    public static Object getInstance(Class cls) {
        Object singleton = map.get(cls);
        if(singleton != null) {
            return singleton;
        }
        synchronized (SingletonRegistry.class) {
            singleton = map.get(cls);
            if (singleton == null) {
                try {
                    Constructor ct = cls.getDeclaredConstructor();
                    ct.setAccessible(true);
                    singleton = ct.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                map.put(cls, singleton);
            }
        }
        return singleton;
    }

    public static void clearAllInstances() {
        synchronized (SingletonRegistry.class) {
            map.clear();
        }
    }
}